<?php
/**
 * XuYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Message block Class for web terminal
 * @author Wayne Yu
 */
class Msgblock {
	/**
	 * Construnct function of this class
	 * @param array $params
	 */
	public function __construct($params = array()){
		//Set the super object
		$this->CI =& get_instance();
		
		//Load the lib required
		$this->CI->load->library('session');
		 
		//Initialize the msg block in session
		$msgArr = $this->CI->session->userdata('SucMsg');
		if(!is_array($msgArr)){
			$this->CI->session->set_userdata('SucMsg', array());
		}
			$msgArr = $this->CI->session->userdata('ErrMsg');
		if(!is_array($msgArr)){
			$this->CI->session->set_userdata('ErrMsg', array());
		}
	}

	/**
	 * Add successs message
	 * @return void
	 */
	public function addSuccess($msg = ''){
		$this->_addSucMsg($msg);
		return;
	}
	
	/**
	 * Add error message
	 */
	public function addError($msg = ''){
		$this->_addErrMsg($msg);
		return;
	}
	
	/**
	 * Get message
	 * @return void
	 */
	public function getMsg(){
		$msg = NULL;
		$msg = $this->_popErrMsg();
		if($msg == NULL){
			$msg = $this->_popSucMsg();
		}
		return $msg;
	}
	
	/**
	 * Clear the message block
	 * @param string $type : default(Clear both),suc(Clear Success),err(Clear Error)
	 * @return void
	 */
	public function clearMsg($type = ''){
		switch ($type){
			case 'suc':
				$this->_clearSucMsg();
				break;
			case 'err':
				$this->_clearErrMsg();
				break;
			default:
				$this->_clearSucMsg();
				$this->_clearErrMsg();
		}
		return;
	}
	
	/**
	 * Add success message in the session
	 */
	private function _addSucMsg($msg){
		$msgArr = $this->CI->session->userdata('SucMsg');
		if(!is_array($msgArr)){
			return;
		}
		array_push($msgArr, $msg);
		$this->CI->session->set_userdata('SucMsg', $msgArr);
		return;
	}
	
	/**
	 * Add error message in the session
	 */
	private function _addErrMsg($msg){
		$msgArr = $this->CI->session->userdata('ErrMsg');
		if(!is_array($msgArr)){
			return;
		}
		array_push($msgArr, $msg);
		$this->CI->session->set_userdata('ErrMsg', $msgArr);
		return;
	}
	
	/**
	 * Pop out the success message
	 */
	private function _popSucMsg(){
		$msgArr = $this->CI->session->userdata('SucMsg');
		if(!is_array($msgArr)){
			return;
		}
		return array_pop($msgArr);
	}
	
	/**
	 * Pop out the error message
	 */
	private function _popErrMsg(){
		$msgArr = $this->CI->session->userdata('ErrMsg');
		if(!is_array($msgArr)){
			return;
		}
		return array_pop($msgArr);
	}
	
	/**
	 * clear the success message in the session
	 */
	private function _clearSucMsg(){
		$this->CI->session->set_userdata('SucMsg', array());
		return;
	}
	
	/**
	 * clear the error message in the session
	 */
	private function _clearErrMsg(){
		$this->CI->session->set_userdata('ErrMsg', array());
		return;
	}
}